<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>转盘</title>
    <style>
      .main {
        display: flex;
        width: 320px;
        flex-wrap: wrap;
      }
      .item {
        width: 100px;
        height: 100px;
        background-color: #ddd;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2px solid #fff;
      }
      .item.active {
        background-color: #999;
      }
      .item.btn {
        background-color: green;
        color: #fff;
      }
    </style>
  </head>
  <body>
    <div class="main"></div>

    <script>
      window.onload = () => {
        const data = {
          jp: [
            { name: "代金券1" },
            { name: "代金券2", is: true },
            { name: "代金券3" },
            { name: "代金券4" },
            { name: "代金券5" },
            { name: "代金券6" },
            { name: "代金券7" },
            { name: "代金券8" },
          ],
        };

        const main = document.querySelector(".main");
        main.innerHTML = data.jp
          .map(
            (v) =>
              `<div class="item" ${v.is ? "is='true'" : ""}>${v.name}</div>`
          )
          .join("");

        const btnEl = document.createElement("div");
        btnEl.className = "item btn";
        btnEl.innerHTML = "抽奖";

        main.insertBefore(btnEl, main.children[4]);

        let isRunning = false;
        let itemIndex = 0;

        const spinWheel = () => {
          const nodesList = [...main.childNodes].filter(
            (v) => !v.classList.contains("btn")
          );
          const spinOrder = [0, 1, 2, 4, 7, 6, 5, 3];
          const spinItems = spinOrder.map((v) => nodesList[v]);

          if (!spinItems[itemIndex]) {
            itemIndex = 0;
          }

          const active1 = main.querySelector(".active");
          active1 && active1.classList.remove("active");

          spinItems[itemIndex].classList.add("active");

          if (!isRunning && spinItems[itemIndex].getAttribute("is")) {
            clearInterval(intervalId);
          }

          itemIndex++;
        };

        let intervalId;
        btnEl.onclick = () => {
          if (isRunning) return;

          isRunning = true;
          intervalId = setInterval(spinWheel, 100);

          setTimeout(() => {
            isRunning = false;
          }, 3000);
        };
      };
    </script>
  </body>
</html>
